package com.jzg.mvc.biz.cab.card;

import com.jfinal.core.Path;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.jzg.common.controller.BaseController;
import com.jzg.common.model.biz.CabCard;
import com.jzg.common.util.UuidUtil;

@Path(value = "/biz/cab/card", viewPath = "/views/biz/cab/card")
public class CabCardController extends BaseController {

	protected final Log LOG = Log.getLog(getClass());

	public void index() {
		this.setAttr("cabId", this.getPara("cabId"));
		render("list.html");
	}

	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String cabId = getPara("cabId");
		String sqlExceptSelect = " FROM " + CabCard.TABLE_NAME + " O  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.LABEL LIKE '%" + keyword + "%' OR   O.CODE '%" + keyword + "%' ) ";
		}
		if (!StrKit.isBlank(cabId)) {
			sqlExceptSelect += " AND O.cabId='"+cabId+"' ";
		}
		sqlExceptSelect += "  ORDER BY   O.SERIAL asc ";
		Page<CabCard> page = CabCard.dao.paginate(pageNumber, pageSize, "select * ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}

	/***
	 * 保存
	 */
	public void save() {
		CabCard cabCard = getModel(CabCard.class);
		if (StrKit.notBlank(cabCard.getId())) {
			CabCard module = CabCard.dao.findFirst("SELECT * FROM " + CabCard.TABLE_NAME + " WHERE CABID=? and VALUE=? AND ID!=?", cabCard.getCabId(),cabCard.getValue(),cabCard.getId());
			if (module != null) {
				renderError("值已存在！");
				return;
			}
			if (cabCard.update()) {
				renderSuccess("更新成功！");
			} else {
				renderError("更新失败！");
			}
		} else {
			CabCard module = CabCard.dao.findFirst("SELECT * FROM " + CabCard.TABLE_NAME + " WHERE CABID=? AND VALUE=? ", cabCard.getCabId(),cabCard.getValue());
			if (module != null) {
				renderError("名称已存在！");
				return;
			}
			cabCard.setId(UuidUtil.getUUID());
			if (cabCard.save()) {
				renderSuccess("保存成功！");
			} else {
				renderError("保存失败！");
			}
		}

	}

	/***
	 * 删除
	 * @throws Exception
	 */
	public void delete() throws Exception {
		String id = getPara("id");
		CabCard cabCard = CabCard.dao.findById(id);
		if (cabCard != null) {
			if (cabCard.delete()) {
				renderSuccess("删除成功！");
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
}
